<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class GoodsContentManager extends Model
{
  protected $table = 'goods_content_manager';
  protected $autoWriteTimestamp = true;

  public function goods()
  {
    return $this->belongsTo('Goods', 'goods_id');
  }

  /**
   * 处理内容中的授权部分
   * @param string $content 原始内容 
   * @param bool $hasAuth 是否有权限
   * @return string 处理后的内容
   */
  public static function handleAuthContent($content, $hasAuth = false)
  {
    return $hasAuth ? $content : '需要购买后查看内容';
  }

  /**
   * 内容类型列表
   * @return array
   */
  public static function getContentTypeList()
  {
    return [
      'text'           => '图文',
      'multi_chapter'  => '多章节',
      'chapter_groups' => '分组多章节',
      'file'           => '单文件下载',
      'multi_file'     => '多文件下载'
    ];
  }


  /**
   * 检查内容是否收费
   * @return bool
   */
  public function isCharged()
  {
    // 如果商品价格为0，则内容免费
    if ($this->goods && $this->goods->price <= 0) {
      return false;
    }

    // 如果内容类型为text，则直接遵循商品价格设置
    if ($this->content_type == 'text') {
      return true;
    }

    return true;
  }

  /**
   * 检查用户是否有权限查看内容
   * @param int $userId 用户ID
   * @return bool
   */
  public function canUserView($userId)
  {
    if (!$userId) {
      return false;
    }

    $user = User::find($userId);
    if (!$user) {
      return false;
    }

    // 如果内容不收费，则可以查看
    if (!$this->isCharged()) {
      return true;
    }

    // 检查用户是否有权限查看
    return $user->canViewContent($this->id);
  }
}
